using System;
using System.Data;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace JHEMR.EMREdit
{
    public partial class UCExamApplyList : UserControl
    {
        [DllImport("HisBrowser", SetLastError = true)]
        static extern void MdcClose();
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern void MdcSetFileServer(string sFileServer);
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern void MdcSetFileServerPath(string sFileServerPath);
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern int MdcConnect(string sServer, string sDatabase);
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern bool MdcGetRecheckCode(string sHisID, [Out, MarshalAs(UnmanagedType.LPArray)] char[] sReCheckCodeList, int nBufSize);
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern bool MdcGetFieldValue(string sRecheckCode, string FieldName, [Out, MarshalAs(UnmanagedType.LPArray)] char[] strBuff, int nBufSize);
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern int MdcGetImages(string strReCheckCode, string sLocalDirectory);
        
        [DllImport("HisBrowser", SetLastError = true)]
        static extern int MdcShowImages(string strReCheckCode);

        private DataSet m_dsSetting = new DataSet();
        private string m_CurPatientID;
        private int m_CurVisitID;
        public string m_strEXAM_NO = string.Empty;
        public string m_strEXAM_CLASS = String.Empty;
        public string m_strExamClass_Nk = String.Empty;
        string strUrlSql = string.Empty;

        public UCExamApplyList()
        {
            InitializeComponent();
        }

        public void setPatient(string strPatientID, int intVisitID)
        {
            m_CurPatientID = strPatientID;
            m_CurVisitID = intVisitID;
            DataLoad();
        }

        private void DataLoad()
        {
            DataSet objDataSet = new DataSet();
            objDataSet = EmrSysWebservices.EmrSysWebservicesUse.myEmrGetExamMaster(m_CurPatientID, chkAll.Checked ? 0 : m_CurVisitID);
            
            if (objDataSet.Tables.Count > 0 && objDataSet.Tables[0].Rows.Count > 0)
            {
                DataTable objTable = objDataSet.Tables[0];
                if (objTable.Rows[0]["exam_no"] != DBNull.Value)
                    m_strEXAM_NO = objTable.Rows[0]["exam_no"].ToString();
                if (objTable.Rows[0]["exam_class"] != DBNull.Value)
                    m_strEXAM_CLASS = objTable.Rows[0]["exam_class"].ToString();

                foreach (DataRow dr in objDataSet.Tables[0].Rows)
                {
                    dr["performed_by"] = EmrSysCom.EmrSysPubFunction.getDeptName(dr["performed_by"].ToString(), true);
                    dr["req_physician"] = EmrSysCom.EmrSysPubFunction.getDeptName(dr["req_physician"].ToString(), true);
                    dr["REQ_DEPT"] = EmrSysCom.EmrSysPubFunction.getDeptName(dr["REQ_DEPT"].ToString(), true);
                    dgvExamMaster.DataSource = objDataSet.Tables[0].DefaultView;
                }
            }

            foreach (DataGridViewRow row in dgvExamMaster.Rows)
            {
                if (row.Cells["RESULT_STATUS"].Value.ToString() == "采集")
                {
                    DataGridViewCellStyle cellStyle = new DataGridViewCellStyle();
                    cellStyle.BackColor = Color.Wheat;
                    row.DefaultCellStyle = cellStyle;
                }
            }
            
            dgvExamMaster_Click(dgvExamMaster, new EventArgs());
        }

        private void GetCSDataLoad()
        {
            try
            {
                if (m_dsSetting.Tables.Count > 0)
                {
                    DataTable dt = m_dsSetting.Tables[0];
                    string m_strServer = "";
                    string m_strServerPath = "";
                    string m_strDatabase = "";
                    string m_strFieldName = "";
                    string m_strExeFile = "";
                    string m_strTemp = "";
                    int nCurRow = 0;
                    
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        DataRow dr = dt.Rows[i];
                        m_strServer = dr["SERVER"].ToString();
                        m_strServerPath = dr["SERVERPATH"].ToString();
                        m_strDatabase = dr["DATABASE"].ToString();
                        m_strFieldName = dr["FIELDNAME"].ToString();
                        m_strExeFile = dr["EXEFILE"].ToString();
                        
                        MdcSetFileServer(m_strServer);
                        MdcSetFileServerPath(m_strServerPath);
                        int nResult = MdcConnect(m_strServer, m_strDatabase);
                        
                        char[] sReCheckCodeList = new char[256];
                        MdcGetRecheckCode(m_CurPatientID, sReCheckCodeList, 256);
                        String s = new string(sReCheckCodeList);
                        string[] strItems = s.Split(new Char[] { ',' });
                        
                        if (strItems != null)
                        {
                            for (int j = 0; j < strItems.Length; j++)
                            {
                                m_strTemp = strItems[j].ToString().Trim();
                                if (m_strTemp.Length > 0)
                                {
                                    dgvBC.Rows.Add(1);
                                    dgvBC.Rows[nCurRow].Cells[0].Value = dr["CLASSNAME"].ToString();
                                    dgvBC.Rows[nCurRow].Cells[1].Value = m_strTemp;
                                    dgvBC.Rows[nCurRow].Cells[3].Value = i.ToString();
                                    nCurRow++;
                                }
                            }
                        }
                        MdcClose();
                    }
                }
            }
            catch (System.Exception E)
            {
                return;
            }
        }

        private void UCExamApplyList_Load(object sender, EventArgs e) { }

        private void dgvExamMaster_Click(object sender, EventArgs e)
        {
            if (dgvExamMaster.SelectedRows.Count > 0)
            {
                DataGridViewRow objCurRow = dgvExamMaster.SelectedRows[0];
                if (objCurRow.Cells["RESULT_STATUS"].Value.ToString() != "采集")
                {
                    txtExam.Text = "";
                    return;
                }

                string strExamNo = objCurRow.Cells["EXAM_NO"].Value.ToString().Trim();
                string strOrderSn = objCurRow.Cells["ORDER_SN"].Value.ToString().Trim();
                DataSet dtExamReport = EmrSysWebservices.EmrSysWebservicesUse.myEmrGetExamReport(strExamNo);
                
                if (dtExamReport.Tables[0].Rows.Count == 1)
                {
                    string strExamReport = dtExamReport.Tables[0].Rows[0]["exam_report"].ToString();
                    txtExam.Text = strExamReport;

                    if (dtExamReport.Tables[0].Rows[0]["URL_TEXT"] != DBNull.Value)
                        strUrlSql = dtExamReport.Tables[0].Rows[0]["URL_TEXT"].ToString();
                }
            }
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            DataLoad();
        }

        private void dgvExamMaster_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvExamMaster.SelectedRows.Count > 0)
            {
                strUrlSql = "";
                DataGridViewRow objCurRow = dgvExamMaster.SelectedRows[0];
                
                if (objCurRow.Cells["RESULT_STATUS"].Value.ToString() != "采集")
                {
                    txtExam.Rtf = "";
                    return;
                }

                string strExamNo = objCurRow.Cells["EXAM_NO"].Value.ToString().Trim();
                m_strExamClass_Nk = objCurRow.Cells["exam_class"].Value.ToString().Trim();
                
                DataSet dtExamReport = EmrSysWebservices.EmrSysWebservicesUse.myEmrGetExamReport(strExamNo);
                if (dtExamReport.Tables[0].Rows.Count == 1)
                {
                    string strExamReport = dtExamReport.Tables[0].Rows[0]["exam_report"].ToString();
                    txtExam.Text = strExamReport;
                    m_strEXAM_NO = strExamNo;

                    if (dtExamReport.Tables[0].Rows[0]["URL_TEXT"] != DBNull.Value)
                        strUrlSql = dtExamReport.Tables[0].Rows[0]["URL_TEXT"].ToString();
                }
            }
        }

        private void btnMedcom_Click(object sender, EventArgs e)
        {
            if (m_strExamClass_Nk == "消化科考勤")
            {
                System.Diagnostics.Process Proc;
                try
                {
                    // 启动外部程序
                }
                catch (System.ComponentModel.Win32Exception ee)
                {
                    MessageBox.Show("系统找不到指定的程序文件。\r" + ee);
                    return;
                }
            }
            else
            {
                if (strUrlSql.Length > 0)
                {
                    object[] objParam = new object[1];
                    objParam[0] = "GETPACSPICURL";
                    string strUidAddPwd = EmrSysWebservices.EmrSysWebservicesUse.myEmrGenralStr(objParam);
                    string strIEUrl = "http://10.1.1.76/ami/html/webviewer.html?viewall&ris_exam_id=" + strUrlSql + strUidAddPwd;
                    
                    try
                    {
                        System.Diagnostics.Process p = new System.Diagnostics.Process();
                        p.StartInfo.FileName = "IEXPLORE.EXE";
                        p.StartInfo.Arguments = strIEUrl;
                        p.Start();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("打开图象错误！");
                    }
                }
                else
                {
                    MessageBox.Show("考勤没有图象！");
                }
            }
        }

        private void dgvBC_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvBC.SelectedRows.Count > 0)
            {
                DataGridViewRow objCurRow = dgvBC.SelectedRows[0];
                DataTable dt = m_dsSetting.Tables[0];
                DataRow dr = dt.Rows[Convert.ToInt32(objCurRow.Cells[3].Value.ToString())];
                
                string m_strServer = dr["SERVER"].ToString();
                string m_strServerPath = dr["SERVERPATH"].ToString();
                string m_strDatabase = dr["DATABASE"].ToString();
                string m_strFieldName = dr["FIELDNAME"].ToString();
                string m_strExeFile = dr["EXEFILE"].ToString();
                
                MdcSetFileServer(m_strServer);
                MdcSetFileServerPath(m_strServerPath);
                int nResult = MdcConnect(m_strServer, m_strDatabase);
                
                char[] strbuf = new char[1024];
                MdcGetFieldValue(objCurRow.Cells[1].Value.ToString(), m_strFieldName, strbuf, 1024);
                String s = new string(strbuf);
                txtExam.Text = s;
                MdcClose();
            }
        }

        private void dgvBC_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 2) // 看图像
            {
                DataGridViewRow objCurRow = dgvBC.Rows[e.RowIndex];
                DataTable dt = m_dsSetting.Tables[0];
                DataRow dr = dt.Rows[Convert.ToInt32(objCurRow.Cells[3].Value.ToString())];
                
                string m_strServer = dr["SERVER"].ToString();
                string m_strServerPath = dr["SERVERPATH"].ToString();
                string m_strDatabase = dr["DATABASE"].ToString();
                
                MdcSetFileServer(m_strServer);
                MdcSetFileServerPath(m_strServerPath);
                int nResult = MdcConnect(m_strServer, m_strDatabase);
                
                Directory.CreateDirectory(Application.StartupPath + "\\MEDCOM");
                MdcGetImages(objCurRow.Cells[1].Value.ToString(), Application.StartupPath + "\\MEDCOM");
                MdcShowImages(objCurRow.Cells[1].Value.ToString());
            }
        }

        // 假设的控件声明
        private CheckBox chkAll;
        private DataGridView dgvExamMaster;
        private TextBox txtExam;
        private DataGridView dgvBC;
    }
}